package com.ccc.javacv.controller;

import com.ccc.javacv.config.WebContextBinder;
import com.ccc.javacv.service.ConvertService;
import com.ccc.javacv.pojo.ClientInfo;
import com.ccc.javacv.pojo.VideoInfo;
import com.ccc.javacv.response.ResponseResult;
import com.ccc.javacv.response.DataSender;
import com.ccc.javacv.response.HttpEmitterDataSender;
import com.ccc.javacv.util.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.Date;

/***
 * HTTP Streaming REST接口
 */
@RestController
@RequestMapping("/javacv")
public class StreamRestController {

    @Autowired
    private ConvertService convertService;

    /**
     * 测试资源是否可用
     *
     * @param videoInfo 视频播放信息
     * @return 成功
     */
    @GetMapping("test")
    public ResponseResult test(VideoInfo videoInfo) {
        convertService.doConvert(null, videoInfo);
        return ResponseResult.success();
    }

    /**
     * 直接尝试播放 （play by source），输出HTTP Streaming
     *
     * @param videoInfo 视频播放信息
     * @return flv流
     */
    @GetMapping(value = "/live", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public Object live(VideoInfo videoInfo) {
        final ResponseBodyEmitter responseBodyEmitter = new ResponseBodyEmitter(-1L);
        final DataSender dataSender = new HttpEmitterDataSender(responseBodyEmitter);
        final ClientInfo clientInfo = new ClientInfo();
        clientInfo.setDataSender(dataSender);
        clientInfo.setConnectTime(new Date());
        clientInfo.setClientIp(IpUtils.getIpAddress(WebContextBinder.getRequest()));
        convertService.doConvert(clientInfo, videoInfo);
        return responseBodyEmitter;
    }

    /**
     * 播放 （play by taskId），输出HTTP Streaming
     *
     * @param taskId 任务ID
     * @return flv流
     */
    @GetMapping(value = "live/{taskId}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public Object liveTaskId(@PathVariable String taskId) {
        final ResponseBodyEmitter responseBodyEmitter = new ResponseBodyEmitter(-1L);
        final DataSender dataSender = new HttpEmitterDataSender(responseBodyEmitter);
        final ClientInfo clientInfo = new ClientInfo();
        clientInfo.setDataSender(dataSender);
        clientInfo.setConnectTime(new Date());
        clientInfo.setClientIp(IpUtils.getIpAddress(WebContextBinder.getRequest()));
        convertService.mergeClient(taskId, clientInfo);
        return responseBodyEmitter;
    }

}
